package com.jackstraw.jack_base.datasource.elasticsearch.entity.bean;

import co.elastic.clients.elasticsearch.ElasticsearchAsyncClient;
import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.json.JsonpMapper;
import co.elastic.clients.json.jackson.JacksonJsonpMapper;
import co.elastic.clients.transport.ElasticsearchTransport;
import com.jackstraw.jack_base.datasource.common.factory.DataSourceBuildFactory;
import com.jackstraw.jack_base.datasource.elasticsearch.util.ElasticSearchCreateUtil;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;


/**
 * es工厂类
 */
public class ElasticSearchFactory implements DataSourceBuildFactory<ElasticSearchTemplate, ElasticSearchPropertiesEntity> {

    private final JsonpMapper mapper;

    public ElasticSearchFactory() {
        mapper = new JacksonJsonpMapper();
    }

    @Override
    public ElasticSearchTemplate build(String tenantName, String dataSourceName, ElasticSearchPropertiesEntity dataSourceEntity) {

        RestClientBuilder restClientBuilder = ElasticSearchCreateUtil.restClientBuilder(dataSourceEntity);
        RestClient restClient = restClientBuilder.build();
        ElasticsearchTransport elasticsearchTransport = ElasticSearchCreateUtil.elasticsearchTransport(restClient, mapper);
        ElasticsearchClient elasticsearchClient = ElasticSearchCreateUtil.elasticsearchClient(elasticsearchTransport);
        ElasticsearchAsyncClient elasticsearchAsyncClient = ElasticSearchCreateUtil.elasticsearchAsyncClient(elasticsearchTransport);


        ElasticSearchTemplate elasticSearchTemplate = new ElasticSearchTemplate();
        elasticSearchTemplate.setRestClientBuilder(restClientBuilder);
        elasticSearchTemplate.setRestClient(restClient);
        elasticSearchTemplate.setElasticsearchTransport(elasticsearchTransport);
        elasticSearchTemplate.setElasticsearchClient(elasticsearchClient);
        elasticSearchTemplate.setPropertiesEntity(dataSourceEntity);
        elasticSearchTemplate.setElasticsearchAsyncClient(elasticsearchAsyncClient);


        return elasticSearchTemplate;
    }
}
